<!DOCTYPE>
<html >
  <head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>聊天室</title>
    <script src="./js/jquery-1.12.3.min.js"></script>
<link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css"/>
<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<style>
body{
	margin-top:5px;
}
</style>
</head>
  <body>
    <div class="container">
    	<div class="row">
    		<div class="col-md-3" style="width: 20%">
    		<div class="panel panel-primary">
				  <div class="panel-heading">
				    <h3 class="panel-title">当前登录用户</h3>
				  </div>
				  <div class="panel-body">
				    <div class="list-group">
					 <a href="#" class="list-group-item">你好，<span id="user"></span></a>
					 <a href="logout" class="list-group-item">退出</a>
					</div>
				  </div>
				</div>
    			<div class="panel panel-primary" id="online">
				  <div class="panel-heading">
				    <h3 class="panel-title">当前在线的其他用户</h3>
				  </div>
				  <div class="panel-body">
				    <div class="list-group" id="users">
					</div>
				  </div>
				</div>
				<div class="panel panel-primary">
				  <div class="panel-heading">
				    <h3 class="panel-title">群发系统广播</h3>
				  </div>
				  <div class="panel-body">
				    <input type="text" class="form-control"  id="msg" /><br>
				    <button id="broadcast" type="button" class="btn btn-primary">发送</button>
				  </div>
				</div>
    		</div>
  			<div class="col-md-9" style="width: 70%">
  				<div class="panel panel-primary">
				  <div class="panel-heading">
				    <h3 class="panel-title" id="talktitle"></h3>
				  </div>
				  <div class="panel-body">
				    <div class="well" id="log-container" style="height:400px;overflow-y:scroll">
				    
				    </div>
				    	<input type="text" id="myinfo" class="form-control col-md-12" /> <br>
					    <input type="file" id="myFile" onchange="chooseFile()"  class="form-control col-md-12" /> <br>
					  发送给:<select id="toUser">
					  			<option value="">选择要聊天的对象</option>
					  			<option value="Mike">Mike</option>
							    <option value="Jon">Jon</option>
							    <option value="TOM">TOM</option>
				  			</select>
				    	<button id="send" type="button" class="btn btn-primary">发送</button>
				    </div>
				</div>
  			</div>
    	</div>
    </div> 
<script>
Date.prototype.format = function(fmt) { 
     var o = { 
        "M+" : this.getMonth()+1,                 //月份 
        "d+" : this.getDate(),                    //日 
        "h+" : this.getHours(),                   //小时 
        "m+" : this.getMinutes(),                 //分 
        "s+" : this.getSeconds(),                 //秒 
        "q+" : Math.floor((this.getMonth()+3)/3), //季度 
        "S"  : this.getMilliseconds()             //毫秒 
    }; 
    if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
    }
     for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
         }
     }
    return fmt; 
}
	var websocket;
	var source;
	var uid;
    $(document).ready(function() {
    	// 指定websocket路径
    	$.get("/currentuser",function(data){
			source = data.name;
    		uid = data.uid;
    		$("#user").html(source);
	        if ('WebSocket' in window) {
				websocket = new WebSocket("ws://localhost:8080/webSocket/"+source);
			}
			websocket.onmessage = function(event) {
	        	var data=JSON.parse(event.data);
	        	if(undefined==data.source||data.source.length==0){
	        		console.log("----未读消息有：",data,"条。")
	        		return ;
				}
				debugger
				// 普通消息 接收服务端的实时消息并添加到HTML页面中
				var _source = data.source;
				if(_source==source){
					_source="我";
				}
				if(data.msgType==0){
					$("#log-container").append("<div class='bg-info'><label class='text-danger'>"+_source+"&nbsp;"+data.createTime+"</label><div class='text-success'>"+data.text+"</div></div><br>");
				}else {
					$("#log-container").append("<div class='bg-info'><label class='text-danger'>"+_source+"&nbsp;"+data.createTime+"</label><div class='text-success'><img src='"+data.data+"' style='width:50%'></img></div></div><br>");
				}

				// 滚动条滚动到最低部
				scrollToBottom();
				var read=data.read;
				if(read==0 && data.target==source){
					// 如果是未阅读的消息且只自己的未读消息时，则发送 ack 确认标识，告诉服务端该消息我已经阅读过了
					var ack_data={};
					ack_data["id"]=data.id;
					ack_data["strategy"]="ack";
					ack_data["source"]=data.source;
					ack_data["target"]=data.target;
					websocket.send(JSON.stringify(ack_data));
				}
	        };
	        $.post("/onlineusers?currentuser="+source,function(data){
    		for(var i=0;i<data.length;i++)
    			$("#users").append('<a href="#" onclick="talk(this)" class="list-group-item">'+data[i]+'</a>');
    		});
    	
    	});


        $("#toUser").change(function(e){
			var target = $(this).children('option:selected').val();
			if(source==target){
				alert("不能给自己发消息!");
				return false;
			}
			if(undefined==target||target.trim().length==0){
				return false;
			}
			$("#log-container").html("");
			var data = {};
			data["source"] = source;
			data["target"] = target;
			data["text"] = "";
			data["strategy"]="history";
			websocket.send(JSON.stringify(data));
		});
        
        $("#send").click(function() {
			var target = $("#toUser").find("option:selected").val();
			if(undefined==target||target.trim().length==0){
				alert("请选择要发送的人!");
				return false;
			}
			debugger
			if(source==target){
				alert("不能给自己发消息!");
				return false;
			}
			var msg=$("#myinfo").val();
			if(undefined==msg||msg.trim().length==0){
				alert("请输入要发送的消息!");
				return false;
			}
			var data = {};
			data["source"] = source;
			data["target"] = target;
			data["text"] = msg;
			data["msgType"]=0;
			websocket.send(JSON.stringify(data));
			$("#log-container").append("<div class='bg-success'><label class='text-info'>我&nbsp;" + new Date().format("yyyy-MM-dd hh:mm:ss") + "</label><div class='text-info'>" + $("#myinfo").val() + "</div></div><br>");
			scrollToBottom();
			$("#myinfo").val("");
		});

    });

	//发送图片消息
	function chooseFile() {
		var target = $("#toUser").find("option:selected").val();
		if(undefined==target||target.trim().length==0){
			alert("请选择要发送的人!");
			clearFile();
			return false;
		}
		var files = document.querySelector("#myFile").files
		if(files.length>0){
			var fileReader = new FileReader();
			var fileName = files[0].name;
			fileReader.readAsDataURL(files[0])
			fileReader.onload=function (e) {
				var data = {};
				data["source"] = source;
				data["target"] = target;
				data["text"] = e.target.result;
				data["msgType"]=1;
				data["fileName"]=fileName;
				websocket.send(JSON.stringify(data));
				$("#log-container").append("<div class='bg-info'><label class='text-danger'>我&nbsp;" + new Date().format("yyyy-MM-dd hh:mm:ss") + "</label><div class='text-success'><img src='"+e.target.result+"' style='width:50%'></img></div></div><br>");
				scrollToBottom();
			}
		}
		clearFile();
	}

	function clearFile(){
		var file = $('#myFile')[0];
		if(file.outerHTML){
			file.outerHTML = file.outerHTML;
		}else{
			file.value = '';
		}
	}

	function talk(a){
		$("#talktitle").text("与"+a.innerHTML+"的聊天");
		$("body").data("target",a.innerHTML);
		$.post("/getHistoryRecord?source="+$("#user").html()+"&target="+a.innerHTML,function(data){
		   alert(data);
		});
	}
   function scrollToBottom(){
		var div = document.getElementById('log-container');
		div.scrollTop = div.scrollHeight;
	}
</script>    
    
  </body>
</html>
